<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/9/10 9:40
 */
include_once dirname(dirname(dirname(dirname(__FILE__)))) . '/mgtv_v2/models/public_model_exec.class.php';
include_once dirname(dirname(dirname(__FILE__))) . "/common.php";
\ns_core\m_load::load_old("nn_logic/clip_task/clip_servicers.class.php");
\ns_core\m_load::load('ns_core.m_mediainfo');
\ns_core\m_load::load('ns_model.clip.clip_task_model');
define('TASK_C_STATE_ADD', 'add');
define('TASK_C_STATE_HANDLE', 'handle');
define('TASK_C_STATE_WAIT', 'wait');
define('TASK_C_STATE_OK', 'ok');
define('TASK_C_STATE_GET_MEDIA_URL_SUCC', 'get_media_url_succ');
define('TASK_C_STATE_GET_MEDIA_URL_FAIL', 'get_media_url_fail');
define('TASK_C_STATE_DOWNLOAD', 'download');
define('TASK_C_STATE_DOWNLOAD_SUCC', 'download_succ');
define('TASK_C_STATE_DOWNLOAD_FAIL', 'download_fail');
define('TASK_C_STATE_CLIPING', 'cutting');
define('TASK_C_STATE_CLIP_SUCC', 'clip_succ');
define('TASK_C_STATE_CLIP_FAIL', 'clip_fail');
define('TASK_C_STATE_CANCEL', 'cancel');
define('TASK_C_STATE_FAIL', 'fail');
define('TASK_C_STATE_C2_HANDLE', 'c2_handle');
define('TASK_C_STATE_C2_SUCC', 'c2_ok');
define('TASK_C_STATE_C2_FAIL', 'c2_fail');
define('TASK_C_STATE_C2_DELETE_HANDLE', 'c2_delete_handle');
define('TASK_C_STATE_C2_DELETE_SUCC', 'c2_delete_ok');
define('TASK_C_STATE_C2_DELETE_FAIL', 'c2_delete_fail');
//DRM
define('TASK_C_STATE_DRM_SUCC', 'drm_ok');
define('TASK_C_STATE_DRM_FAIL', 'drm_fail');
define('TASK_C_STATE_GET_DRM_KEY_SUCC', 'get_drm_key_succ');
define('TASK_C_STATE_GET_DRM_KEY_FAIL', 'get_drm_key_fail');
//clip  drm
define('TASK_C_STATE_CLIP_DRM_SUCC', 'drm_encrypt_ok');
define('TASK_C_STATE_CLIP_DRM_FAIL', 'drm_encrypt_fail');
define('TASK_C_STATE_CLIP_DRM_LOADING', 'drm_encrypt_loading');

//clip  转码 encode
define('TASK_C_STATE_CLIP_ENCODE_SUCC', 'clip_encode_ok');
define('TASK_C_STATE_CLIP_ENCODE_FAIL', 'clip_encode_fail');
define('TASK_C_STATE_CLIP_ENCODE_LOADING', 'clip_encode_loading');
define('TASK_C_STATE_CLIP_ENCODE_WAIT', 'clip_encode_wait');

//clip 上传 upload
define('TASK_C_STATE_CLIP_UPLOADING', 'uploading');
define('TASK_C_STATE_CLIP_UPLOAD_SUC', 'upload_suc');
define('TASK_C_STATE_CLIP_UPLOAD_FAIL', 'upload_fail');

//clip  直播转点播 encode
define('TASK_C_STATE_LIVE_TO_MEDIA_FAIL', 'live_to_media_fail');
define('TASK_C_STATE_LIVE_TO_MEDIA_LOADING', 'live_to_media_loading');
define('TASK_C_STATE_LIVE_TO_MEDIA_WAIT', 'live_to_media_wait');
/**
 * 切片公共类
 * @author liangpan
 * @date 2015-12-25
 */
class clip
{
    private $sp_id = null;
    private $cp_id = null;
    private $sp_config = null;
    private $arr_params = null;
    public $obj_dc = null;
    private $function = null;
    private $obj_dom = null;
    private $program_name = '';
    private $content_description = '';
    private $drm_ext_info = '';
    private $cp_config = null;
    private $error_info = null;
    private $mode_index = array(
        'std'=>'01',
        'hd'=>'02',
        'low'=>'03',
        '4k'=>'04',
    );
    public $redis_lock_timeout = 5;//redis锁默认5S

    public $task_state_arr = array(
        TASK_C_STATE_ADD => '添加任务',//执行成功
        TASK_C_STATE_HANDLE => '任务已下发',//任务已下发（被切片工具取走）
        TASK_C_STATE_WAIT => '等待下发',//执行成功
        TASK_C_STATE_OK => '上报成功',//执行成功
        TASK_C_STATE_GET_MEDIA_URL_SUCC => '取片源下载地址成功',
        TASK_C_STATE_GET_MEDIA_URL_FAIL => '取片源下载地址失败',
        TASK_C_STATE_DOWNLOAD => '下载影片',//下载影片
        TASK_C_STATE_DOWNLOAD_SUCC => '下载成功',//下载影片
        TASK_C_STATE_DOWNLOAD_FAIL => '下载失败',//下载影片
        TASK_C_STATE_CLIPING => '正在切片',//正在切片
        TASK_C_STATE_CLIP_SUCC => '切片成功',
        TASK_C_STATE_CLIP_FAIL => '切片失败',
        TASK_C_STATE_CANCEL => '任务已取消',//任务取消
        TASK_C_STATE_FAIL => '切片失败',//切片失败
        TASK_C_STATE_C2_HANDLE => '执行注入',
        TASK_C_STATE_C2_SUCC => '注入成功',
        TASK_C_STATE_C2_FAIL => '注入失败',
        TASK_C_STATE_C2_DELETE_HANDLE => '等待删除已注入片源',
        TASK_C_STATE_C2_DELETE_SUCC => '删除已注入片源成功',
        TASK_C_STATE_C2_DELETE_FAIL => '删除已注入片源失败',
        TASK_C_STATE_DRM_SUCC => '注入DRM成功',
        TASK_C_STATE_DRM_FAIL => '注入DRM失败',
        TASK_C_STATE_GET_DRM_KEY_SUCC => '获取DRM密钥成功',
        TASK_C_STATE_GET_DRM_KEY_FAIL => '获取DRM密钥失败',
        TASK_C_STATE_CLIP_DRM_SUCC  => 'DRM加密成功',
        TASK_C_STATE_CLIP_DRM_FAIL => 'DRM加密失败',
        TASK_C_STATE_CLIP_DRM_LOADING => '正在DRM加密',
        TASK_C_STATE_CLIP_UPLOADING  => '上传中',
        TASK_C_STATE_CLIP_UPLOAD_SUC => '上传成功',
        TASK_C_STATE_CLIP_UPLOAD_FAIL => '上传失败',
        TASK_C_STATE_CLIP_ENCODE_SUCC => '文件转码成功',
        TASK_C_STATE_CLIP_ENCODE_FAIL => '文件转码失败',
        TASK_C_STATE_CLIP_ENCODE_LOADING => '正在文件转码',
        TASK_C_STATE_CLIP_ENCODE_WAIT => '等待文件转码',
        TASK_C_STATE_LIVE_TO_MEDIA_FAIL => '直播转点播失败',
        TASK_C_STATE_LIVE_TO_MEDIA_LOADING => '正在直播转点播',
        TASK_C_STATE_LIVE_TO_MEDIA_WAIT => '等待直播转点播',
    );

    /**
     * @return the $error_info
     */
    public function get_error_info()
    {
        return $this->error_info;
    }


    /**
     * @param $error_info
     * @return mixed
     */
    private function set_error_info($error_info)
    {
        $this->error_info[] = $error_info;
        return $error_info;
    }

    public function __construct($sp_id = null, $arr_params = null,$function = null,$cp_id = null)
    {
        $this->sp_id = $sp_id;
        $this->cp_id = $cp_id;
        $this->arr_params = $arr_params;
        $this->obj_dc = \m_config::get_dc();
        $this->function = $function;
    }

    /**
     * 返回数据数组
     * @param int $ret
     * @param string $str_desc //英文描述
     * @param null $error_info //错误描述
     * @return array
     */
    private function _return_data($ret=200,$str_desc='',$error_info=null)
    {
        return array(
            'ret'=>$ret,
            'reason'=>$str_desc,
            'error_info'=>$error_info,
        );
    }

    /**
     * 获取CP配置（单个CP）
     * @param string $cp_id
     * @return boolean
     * @author liangpan
     * @date 2015-12-25
     */
    private function _get_cp_config($cp_id=null)
    {
        if(strlen($cp_id) < 1)
        {
            $this->set_error_info($this->_return_data('404','CP ID is empty',"cp id 错误，传入参数为：".var_export($cp_id,true)));
            return false;
        }
        $result_info=nl_cp::query_by_id($this->obj_dc, $cp_id);
        if($result_info['ret'] !=0)
        {
            $this->set_error_info($this->_return_data('404','sql query cp error',"cp id 查询 sql 错误：".var_export($result_info['reason'],true)));
            return false;
        }
        if(isset($result_info['data_info']['nns_config']) && strlen($result_info['data_info']['nns_config']) >0)
        {
            $result_info_config = json_decode($result_info['data_info']['nns_config'],true);
            if(is_array($result_info_config) && !empty($result_info_config))
            {
                $this->cp_config = $result_info_config;
                $this->cp_config['base_cp_name'] = $result_info['data_info']['nns_name'];
            }
        }
        return true;
    }

    /**
     * 获取SP配置（单个SP）
     * @param string $sp_id
     * @return boolean
     * @author liangpan
     * @date 2015-12-25
     */
    private function _get_sp_config($sp_id=null)
    {
        if(strlen($sp_id) < 1)
        {
            $this->set_error_info($this->_return_data('404','SP ID is empty',"sp id 错误，传入参数为：".var_export($sp_id,true)));
            return false;
        }
        $result_info=nl_sp::query_by_id($this->obj_dc, $sp_id);
        if($result_info['ret'] !=0)
        {
            $this->set_error_info($this->_return_data('404','sql query sp error',"sp id 查询 sql 错误：".var_export($result_info['reason'],true)));
            return false;
        }
        if(isset($result_info['data_info'][0]['nns_config']) && strlen($result_info['data_info'][0]['nns_config']) >0)
        {
            $result_info_config = json_decode($result_info['data_info'][0]['nns_config'],true);
            if(is_array($result_info_config) && !empty($result_info_config))
            {
                $this->sp_config = $result_info_config;
                $temp_bind_cp_conf = explode(',', $result_info['data_info'][0]['nns_bind_cp']);
                if(is_array($temp_bind_cp_conf) && !empty($temp_bind_cp_conf))
                {
                    foreach ($temp_bind_cp_conf as $val)
                    {
                        if(strlen($val) <1)
                        {
                            continue;
                        }
                        $this->sp_config['bind_cp_conf'][]=$val;
                    }
                }
                unset($temp_bind_cp_conf);
            }
        }
        return true;
    }


    /**
     * 公共反馈错误信息
     * @param string $function
     * @param boolean $is_need_header
     * @author liangpan
     * @date 2015-12-25
     */
    private function _return_auto_error_info( $function = 'public', $is_need_header = true)
    {
        $http_code = '404';
        $reason = '';
        $data = null;
        if(isset($this->error_info) && is_array($this->error_info))
        {
            foreach ($this->error_info as $val)
            {
                $reason.="{$val['reason']};";
            }
        }
        $reason = trim($reason,';');
        $this->_bulid_result($http_code, $reason, $data, $function , $is_need_header);
    }


    /**
     * 获取单条切片任务数据
     * @author liangpan
     * @date 2015-12-25
     */
    public function get_clip_task()
    {
        \m_config::write_clip_receive_log('------' . $this->function . '------', $this->sp_id);
        $flag=$this->_get_sp_config($this->sp_id);
        if(!$flag)
        {
            $this->_return_auto_error_info($this->function);
        }
        if(isset($this->sp_config['clip_import_model']) && $this->sp_config['clip_import_model'] == 1)
        {
            \m_config::write_clip_receive_log('新模式切片开始', $this->sp_id);
            $this->get_clip_task_v2();
        }
        //切片获取任务REDIS模式
        if(isset($this->sp_config['clip_import_model']) && $this->sp_config['clip_import_model'] == 2)
        {
            \m_config::write_clip_receive_log('REDIS获取切片任务开始', $this->sp_id);
            $this->get_clip_task_v3();
        }
        \m_config::write_clip_receive_log('老模式切片开始', $this->sp_id);
        $nns_new_dir = isset($this->arr_params['nns_new_dir']) ? (int)$this->arr_params['nns_new_dir'] : 0;
        $tom3u8_id = isset($this->arr_params['tom3u8_id']) ? $this->arr_params['tom3u8_id'] : '';
        $task_info = \clip_task_model::get_task($this->sp_id);
        if (!is_array($task_info))
        {
            $this->_bulid_result('404', 'no task', null, $this->function);
            exit();
        }
        $dt = date('Y-m-d H:i:s');
        //更新任务状态:任务已被取走
        $set_state = array (
            'nns_state' => TASK_C_STATE_HANDLE,
            'nns_desc' => $this->task_state_arr[TASK_C_STATE_HANDLE],
            'nns_start_time' => $dt,
            'nns_modify_time' => $dt,
            'nns_tom3u8_id'   =>$tom3u8_id
        );
        //查询此服务器id是否存在 不存在自动添加
        $result = \nl_clip_servicers::query_by_id($this->obj_dc, $tom3u8_id);
        if (!isset($result['data_info']) || empty($result['data_info']))
        {
            $params['nns_id']=np_guid_rand();
            $params['nns_tom3u8_id']=$tom3u8_id;
            \nl_clip_servicers::add($this->obj_dc, $params);
        }

        $set_state['nns_new_dir'] = $nns_new_dir;

        \m_config::write_clip_receive_log('更新内容：' . var_export($set_state, true), $this->sp_id);

        \clip_task_model::update_task($task_info['nns_id'], $set_state);
        //任务日志
        $task_log = array (
            'nns_task_id' => $task_info['nns_id'],
            'nns_state' => TASK_C_STATE_HANDLE,
            'nns_desc' => $this->task_state_arr[TASK_C_STATE_HANDLE]
        );
        \m_config::write_clip_receive_log('任务日志内容：' . var_export($task_log, true), $this->sp_id);
        $rs = \clip_task_model::add_task_log($task_log);
        \m_config::write_clip_receive_log('添加日志结果：' . var_export($rs, true), $this->sp_id);
        $this->_bulid_result('200', 'OK', $task_info['nns_content'], $this->function);
    }

    /**
     * 获取单条切片任务数据（片源获取切片信息）
     * @author liangpan
     * @date 2015-12-25
     */
    private function get_clip_task_v2()
    {
        \ns_core\m_load::load_old('nn_logic/vod_media/vod_media.class.php');
        \ns_core\m_load::load_old('nn_logic/clip_task/clip_task.class.php');
        if(!is_array($this->sp_config['bind_cp_conf']) || empty($this->sp_config['bind_cp_conf']))
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']获取单条切片任务数据（片源获取切片信息）cp为空：' . var_export($this->sp_config['bind_cp_conf'], true), $this->sp_id);
            $this->_bulid_result('404', 'bind_cp_conf no query', null, $this->function);
            exit();
        }
        $this->cp_id = $this->sp_config['bind_cp_conf'][array_rand($this->sp_config['bind_cp_conf'])];
        $flag=$this->_get_cp_config($this->cp_id);
        if(!$flag)
        {
            $this->_return_auto_error_info($this->function);
        }
        if(isset($this->sp_config['message_import_time_control']) && !empty($this->sp_config['message_import_time_control']))
        {
            $check_allow_download = $this->check_allow_download($this->sp_config['message_import_time_control']);
            if(!$check_allow_download)
            {
                $this->_bulid_result('404', 'no task allow this time download', null, $this->function);
                exit();
            }
        }
        $result = nl_vod_media_v2::query_wait_clip($this->obj_dc,$this->cp_id);
        if($result['ret'] !=0)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']查询切片数据内部错误：' . var_export($result, true), $this->sp_id);
            $this->_bulid_result('404', 'bk inner error', null, $this->function);
            exit();
        }
        if(!is_array($result['data_info']) || empty($result['data_info']))
        {
            $this->_bulid_result('404', 'no task', null, $this->function);
            exit();
        }
        $result=$result['data_info'];
        $result_check = nl_clip_task::check_exsist($this->obj_dc,$result['nns_id']);
        if($result_check['ret'] !=0)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']切片查询是否存在片源内部错误：' . var_export($result_check, true), $this->sp_id);
            $this->_bulid_result('404', 'bk inner error', null, $this->function);
            exit();
        }
        $task_id = empty($result_check['data_info']) ? np_guid_rand() : $result_check['data_info'];
        $flag_media_type = ($result['nns_filetype'] == 'hls') ? 'hls' : 'ts';
        $this->obj_dom = new DOMDocument("1.0", 'utf-8');
        //task xml attr 数组
        $task_array = array(
            'id'=>$task_id,
            'force' => 0,
            'model' => 1,
        );
        $obj_task=$this->make_xml('task',null,$task_array);
        //video xml attr 数组
        $video_array = array(
            'id'=>$result['nns_vod_id'],
            'name' => htmlspecialchars($result['vod_name'], ENT_QUOTES),
            'video_type' => 0,
            'pinyin'=> $result['vod_pinyin'],
        );
        $obj_video=$this->make_xml('video',null,$video_array,$obj_task);
        $obj_index_list=$this->make_xml('index_list',null,null,$obj_video);
        //index xml attr 数组
        $index_array = array(
            'id'=>$result['nns_vod_index_id'],
            'index' => $result['index_index'],
            'name' => htmlspecialchars($result['index_name'], ENT_QUOTES),
            'media_type' => $flag_media_type,
        );
        $obj_index=$this->make_xml('index',null,$index_array,$obj_index_list);
        $obj_media_list=$this->make_xml('media_list',null,null,$obj_index);
        $media_array = array(
            'id'=>$result['nns_id'],
            'name' => $result['nns_name'],
            'file_id' => $result['nns_import_id'],
            'content_id'=> $result['index_import_id'],
            'content_url'=>$result['nns_url'],
            'kbps_index'=>'0'.$this->_get_kbps_index($result['nns_mode']),
            'kbps'=>$result['nns_kbps'],
            'md5'=>clip_task_model::get_media_hash($result['nns_import_id'],$this->cp_id),
            'drm_enabled'=>0,
            'cp_id'=>$this->cp_id,
            'media_type'=>$flag_media_type,
        );
        $this->make_xml('media',null,$media_array,$obj_media_list);
        $str_xml_content = $this->obj_dom->saveXML();
        $add_array = array (
            'nns_id' => $task_id,
            'nns_state' => TASK_C_STATE_HANDLE,
            'nns_desc' => $this->task_state_arr[TASK_C_STATE_HANDLE],
            'nns_video_id' => $result['nns_vod_id'],
            'nns_video_index_id' => $result['nns_vod_index_id'],
            'nns_video_media_id' => $result['nns_id'],
            'nns_org_id' => $this->sp_id,
            'nns_task_type' => 'std',
            'nns_video_type' => 0,
            'nns_priority' => 0,
            'nns_force' => 0,
            'nns_new_dir' => 0,
            'nns_task_name' => $result['nns_name'],
            'nns_content' =>htmlspecialchars($str_xml_content, ENT_QUOTES),
        );
        if(empty($result_check['data_info']))
        {
            $result_add = nl_clip_task::add($this->obj_dc, $add_array);
        }
        else
        {
            unset($add_array['nns_id']);
            $result_add = nl_clip_task::edit($this->obj_dc, $add_array,$task_id);
        }
        if($result_add['ret'] !=0)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']切片数据添加内部错误：' . var_export($result_add, true), $this->sp_id);
            $this->_bulid_result('404', 'bk inner error', null, $this->function);
            exit();
        }
        $result_edit_meida = nl_vod_media_v2::edit($this->obj_dc,array('nns_clip_state'=>2),$result['nns_id']);
        if($result_edit_meida['ret'] !=0)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']修改片源切片状态数据内部错误：' . var_export($result_edit_meida, true), $this->sp_id);
            $this->_bulid_result('404', 'bk inner error', null, $this->function);
            exit();
        }
        //任务日志
        $task_log = array (
            'nns_task_id' => $task_id,
            'nns_state' => TASK_C_STATE_HANDLE,
            'nns_desc' => $this->task_state_arr[TASK_C_STATE_HANDLE]
        );
        \m_config::write_clip_receive_log('[' . $this->function . ']添加任务日志内容：' . var_export($task_log, true), $this->sp_id);
        clip_task_model::add_task_log($task_log);
        $this->_bulid_result('200', 'OK', $str_xml_content, $this->function);
    }
    /**
     * 从redis中获取切片任务
     * @return boolean|unknown
     */
    private function get_clip_task_v3()
    {
        \ns_core\m_load::load_np('np_redis_lock.class.php');
        $redis_obj = nl_get_redis();
        $redis_lock = new np_redis_lock_class($redis_obj);
        //获取锁
        $identifier = $redis_lock->lock($this->sp_id,$this->redis_lock_timeout);
        if($identifier === false)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']队列已经被锁', $this->sp_id);
            $this->_bulid_result('404', 'no task', null, $this->function);
        }
        $result = $redis_obj->lpop($this->sp_id);
        \m_config::write_clip_receive_log('[' . $this->function . ']任务内容为：' . var_export($result, true), $this->sp_id);
        if($result === false)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']没有任务', $this->sp_id);
            $this->_bulid_result('404', 'no task', null, $this->function);
        }
        //解锁
        $redis_lock->unlock($this->sp_id,$identifier);

        $this->_bulid_result('200', 'OK', $result, $this->function);
    }

    /**
     * 判断时间范围是否允许
     * @param string $str_time
     * @return boolean true 允许 | false 不允许
     * @authorliangpan
     * @date 2015-12-25
     */
    private function check_allow_download($str_time)
    {
        $arr_time = explode("|", $str_time);
        if(empty($arr_time) || !is_array($arr_time))
        {
            return true;
        }
        $now_time = intval(str_replace(array(':'), '',date('G:i')));
        foreach ($arr_time as $val)
        {
            $arr_val = explode('-', trim($val));
            if(empty($arr_val) || !is_array($arr_val) || count($arr_val) !=2 || !isset($arr_val[0]) || !isset($arr_val[1]))
            {
                continue;
            }
            $str_begin = intval(str_replace(array(':',"：",' ',' '), '', preg_replace("/^0*/", '',$arr_val[0])));
            $str_end = intval(str_replace(array(':',"：",' ',' '), '', preg_replace("/^0*/", '',$arr_val[1])));
            if($str_begin > $str_end)
            {
                $str_begin=$str_begin^$str_end;
                $str_end=$str_end^$str_begin;
                $str_begin=$str_begin^$str_end;
            }
            if($now_time >= $str_begin && $now_time <= $str_end)
            {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取清晰度对应
     * @param string $mode
     * @return Ambigous <string, multitype:string >
     * @authorliangpan
     * @date 2015-12-25
     */
    private function _get_kbps_index($mode)
    {
        $mode= strtolower($mode);
        $mode_index = '01';
        if(strlen($mode) > 0 && isset($this->mode_index[$mode]))
        {
            $mode_index = $this->mode_index[$mode];
        }
        return $mode_index;
    }

    /**
     * 获取片源下载地址
     * @authorliangpan
     * @date 2015-12-25
     */
    public function get_media_url()
    {
        \m_config::write_clip_receive_log('------取片源下载地址[' . $this->function . ']------', $this->sp_id);
        $task_id = isset($this->arr_params['nns_task_id']) ? $this->arr_params['nns_task_id'] : null;
        $video_id = isset($this->arr_params['nns_video_id']) ? $this->arr_params['nns_video_id'] : null;
        $video_type = isset($this->arr_params['nns_video_type']) ? $this->arr_params['nns_video_type'] : 0;
        $nns_index_id = isset($this->arr_params['nns_index_id']) ? $this->arr_params['nns_index_id'] : null;
        $nns_media_id = isset($this->arr_params['nns_media_id']) ? $this->arr_params['nns_media_id'] : null;
        $nns_new_dir = isset($this->arr_params['nns_new_dir']) ? $this->arr_params['nns_new_dir'] : 0;
        $tom3u8_id = isset($this->arr_params['tom3u8_id']) ? $this->arr_params['tom3u8_id'] : '';
        //判断任务状态
        $task_info = clip_task_model::get_task_by_id($task_id);
        if ($task_info == false)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']未找到该任务(task id:' . $task_id . ')', $this->sp_id);
            $this->_bulid_result('404', 'get task info fail', null, $this->function);
        }
        if ($task_info['nns_state'] == TASK_C_STATE_CANCEL)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']任务已取消(task id:' . $task_id . ')', $this->sp_id);
            $data = '<media id="' . $nns_media_id . '" url="" state="1" reason="task cancel"/>';
            $this->_bulid_result('200', 'OK', $data, $this->function);
        }
        $flag=$this->_get_sp_config($this->sp_id);
        if(!$flag)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']获取SP配置失败任务(task id:' . $task_id . '，spid:'.$this->sp_id.')'.var_export($this->error_info,true), $this->sp_id);
            $this->_return_auto_error_info($this->function);
        }
        $this->cp_id = $task_info['nns_cp_id'];
        $this->_get_cp_config($this->cp_id);

        switch ($video_type)
        {
            case '0':
                $video_type = 'media';
                break;
            case '1':
                $video_type = 'live_media';
                break;
            case '2':
                $video_type = 'file';
                break;
            default:
                $video_type = 'media';
        }
        $queue_model = new ns_model\m_queue_model();
        $result = $queue_model->_get_asset_info_by_cdn_epg_import_id($this->sp_id, $video_type, $nns_media_id,$this->cp_id);
        if($result['ret'] !=0)
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']获取GUID转换(task id:' . $task_id . '，spid:'.$this->sp_id.')'.var_export($result,true), $this->sp_id);
            $this->_return_auto_error_info($this->function);
        }
        if(!isset($result['data_info'][$video_type]['base_info']) || empty($result['data_info'][$video_type]['base_info']) || !is_array($result['data_info'][$video_type]['base_info']))
        {
            \m_config::write_clip_receive_log('[' . $this->function . ']取片源信息失败:'.var_export($result,true), $this->sp_id);
            $this->_bulid_result('404', 'get media info fail', null, $this->function);
        }
        $media_info = $result['data_info'][$video_type]['base_info'];
        $str_get_url='';
        \ns_core\m_load::load_np('np_http_curl.class.php');
        $http_client = new np_http_curl_class();
        if(isset($media_info['nns_cp_id']) && strlen($media_info['nns_cp_id']) > 0 )
        {
            $str_get_url="&cp_id={$media_info['nns_cp_id']}";
        }
        if(!isset($media_info['nns_import_id']) || strlen($media_info['nns_import_id']) <1 )
        {
            $str_get_url.="&media_id={$media_info['nns_id']}";
        }
        $url = $this->sp_config['down_url'] . 'file_id=' . $media_info['nns_import_id'].$str_get_url;
        \m_config::write_clip_receive_log('[' . $this->function . ']从接口取影片下载地址：' . $url, $this->sp_id);
        $result = $http_client->get($url);
        $ret_arr = json_decode($result, true);
        \m_config::write_clip_receive_log('[' . $this->function . ']response:' . $result . ',json_decode数据：' . var_export($ret_arr, true), $this->sp_id);
        $dt = date('Y-m-d H:i:s');
        if ($ret_arr['err'] == '0')
        {
            $down_url = $ret_arr['msg']['download_url'];
            $status = $ret_arr['status'];
            $reason = $ret_arr['reason'];
            $data = '<media id="' . $nns_media_id . '" url="' . $down_url . '" state="0" reason="' . $reason . '"/>';
            $set_state = array (
                'nns_desc' => $this->task_state_arr[TASK_C_STATE_GET_MEDIA_URL_SUCC] . '[' . $url . '][media_url:' . $down_url . ']',
                'nns_state' => TASK_C_STATE_GET_MEDIA_URL_SUCC,
                'nns_modify_time' => $dt,
                'nns_alive_time' => $dt
            );
            $set_state['nns_new_dir'] = $nns_new_dir;
            $set_state['nns_tom3u8_id'] = $tom3u8_id;
            \m_config::write_clip_receive_log('[' . $this->function . ']更新内容：' . var_export($set_state, true), $this->sp_id);
            clip_task_model::update_task($task_id, $set_state);
            //任务日志
            $task_log = array (
                'nns_task_id' => $task_id,
                'nns_state' => TASK_C_STATE_GET_MEDIA_URL_SUCC,
                'nns_desc' => $this->task_state_arr[TASK_C_STATE_GET_MEDIA_URL_SUCC] . '[' . $url . '][media_url:' . $down_url . ']',
                'nns_create_time' => $dt
            );
            clip_task_model::add_task_log($task_log);
            \m_config::write_clip_receive_log('[' . $this->function . ']任务日志：' . var_export($task_log, true), $this->sp_id);
            $this->_bulid_result('200', 'OK', $data, $this->function);
        }
        else
        {
            $set_state = array (
                'nns_desc' => $this->task_state_arr[TASK_C_STATE_GET_MEDIA_URL_FAIL] . '[' . $url . ']',
                'nns_state' => TASK_C_STATE_GET_MEDIA_URL_FAIL,
                'nns_modify_time' => $dt,
                'nns_alive_time' => $dt
            );
            $set_state['nns_new_dir'] = $nns_new_dir;
            \m_config::write_clip_receive_log('[' . $this->function . ']更新内容：' . var_export($set_state, true), $this->sp_id);
            \clip_task_model::update_task($task_id, $set_state);
            //查询此服务器id是否存在 不存在自动添加
            $result = \nl_clip_servicers::query_by_id($this->obj_dc, $tom3u8_id);
            if (!isset($result['data_info']) || empty($result['data_info']))
            {
                $params['nns_id']=np_guid_rand();
                $params['nns_tom3u8_id']=$tom3u8_id;
                \nl_clip_servicers::add($this->obj_dc, $params);
            }
            //任务日志
            $task_log = array (
                'nns_task_id' => $task_id,
                'nns_state' => TASK_C_STATE_GET_MEDIA_URL_FAIL,
                'nns_desc' => $this->task_state_arr[TASK_C_STATE_GET_MEDIA_URL_FAIL] . '[' . $url . ']',
                'nns_create_time' => $dt,
                'nns_modify_time' => $dt
            );
            clip_task_model::add_task_log($task_log);
            \m_config::write_clip_receive_log('[' . $this->function . ']任务日志：' . var_export($task_log, true), $this->sp_id);
            $this->_bulid_result('404', 'get meida url fail', null, $this->function);
        }
    }

    /**
     * cdn切片状态上报
     * @return boolean
     * @authorliangpan
     * @date 2015-12-25
     */
    public function report_clip_status()
    {
        \ns_core\m_load::load_old('nn_logic/vod_media/vod_media.class.php');
        \m_config::write_clip_receive_log('------' . $this->function . '------', $this->sp_id);
        \m_config::write_clip_receive_log('-----请求参数为：' . var_export($this->arr_params, true). '------', $this->sp_id);

        $task_id = isset($this->arr_params['nns_task_id']) ? $this->arr_params['nns_task_id'] : null;
        $state = isset($this->arr_params['nns_state']) ? $this->arr_params['nns_state'] : null;
        $desc = isset($this->arr_params['nns_desc']) ? htmlspecialchars($this->arr_params['nns_desc'], ENT_QUOTES) : null;
        $nns_new_dir = isset($this->arr_params['nns_new_dir']) ? (int)$this->arr_params['nns_new_dir'] : 0;
        $nns_path = isset($this->arr_params['nns_path']) ? $this->arr_params['nns_path'] : null;
        $nns_file_size = isset($this->arr_params['nns_file_size']) ? $this->arr_params['nns_file_size'] : null;
        $nns_file_md5 = isset($this->arr_params['nns_file_md5']) ? $this->arr_params['nns_file_md5'] : null;
        $nns_cdn_policy = isset($this->arr_params['nns_cdn_policy']) ? $this->arr_params['nns_cdn_policy']:null;
        $nns_file_hit = isset($this->arr_params['nns_file_hit']) ? $this->arr_params['nns_file_hit']:null;
        $nns_node_id = isset($this->arr_params['nns_node_id']) ? $this->arr_params['nns_node_id']:null;
        $nns_list_ids = isset($this->arr_params['nns_list_ids']) ? $this->arr_params['nns_list_ids']:null;
        $tom3u8_id = isset($this->arr_params['tom3u8_id']) ? $this->arr_params['tom3u8_id'] : '';
        $dt = date('Y-m-d H:i:s');
        $set_state = array (
            'nns_desc' => $desc,
            'nns_state' => $state,
            'nns_modify_time' => $dt,
            'nns_alive_time' => $dt
        );
        $task_info = clip_task_model::get_task_by_id($task_id);
        if ($task_info == false)
        {
            \m_config::write_clip_receive_log('未找到该任务(task id:' . $task_id . ')', $this->sp_id);
            $this->_bulid_result('404', 'get task info fail', null, $this->function);
        }
        //获取媒资信息
        $import_info = \clip_task_model::get_import_id_by_task_id($this->obj_dc, array($task_id), $this->sp_id);
        if (empty($import_info) || !is_array($import_info) || count($import_info) <1)
        {
            \m_config::write_clip_receive_log('未找到该任务对应的媒资信息(task id:' . $task_id . ')', $this->sp_id);
            $this->_bulid_result('404', 'get task asset info fail', null, $this->function);
        }
        $this->cp_id = $import_info[0]['media_cp_id'];
        $this->_get_cp_config($import_info[0]['media_cp_id']);

        //获取得任务已经取消
        if ($task_info['nns_state'] == TASK_C_STATE_CANCEL)
        {
            \m_config::write_clip_receive_log('任务已取消(task id:' . $task_id . ')', $this->sp_id);

            $data = '<result state="1" reason="task cancel" />';
            //任务日志
            $task_log = array (
                'nns_task_id' => $task_id,
                'nns_state' => TASK_C_STATE_CANCEL,
                'nns_desc' => '切片失败：该任务(task id:' . $task_id . ')已经取消',
                'nns_create_time' => $dt
            );
            clip_task_model::add_task_log($task_log);
            $this->_bulid_result('200', 'OK', $data, $this->function);
        }
        //如果切片完成，生成注入xml文件，执行影片注入命令
        $state = strtolower(trim($state));
        //对失败的记录全局日志
        if($state == TASK_C_STATE_CLIP_DRM_FAIL || $state == TASK_C_STATE_GET_MEDIA_URL_FAIL || $state == TASK_C_STATE_DOWNLOAD_FAIL || $state == TASK_C_STATE_CLIP_FAIL || $state == TASK_C_STATE_C2_DELETE_FAIL|| $state == TASK_C_STATE_CLIP_UPLOAD_FAIL)
        {
            switch ($state)
            {
                case TASK_C_STATE_GET_MEDIA_URL_FAIL:
                    $errors = "获取下载地址失败";
                    break;
                case TASK_C_STATE_CLIP_DRM_FAIL:
                    $errors = "DRM加密失败";
                    break;
                case TASK_C_STATE_DOWNLOAD_FAIL:
                    $errors = "片源下载失败";
                    break;
                case TASK_C_STATE_CLIP_FAIL:
                    $errors = "切片失败";
                    break;
                case TASK_C_STATE_C2_DELETE_FAIL:
                    $errors = "删除切片服务器片源失败";
                    break;
                case TASK_C_STATE_CLIP_UPLOAD_FAIL:
                    $errors = "上传失败";
                    break;
                default :
                    $errors = '获取下载地址失败';
                    break;
            }
            \m_config::write_clip_receive_log('切片上报失败(task id:' . $task_id . ')' . $state, $this->sp_id);
        }

        if(!$this->_get_sp_config($this->sp_id))
        {
            \m_config::write_clip_receive_log('片源状态上报获取sp配置数据内部错误：' . var_export($this->get_error_info(), true), $this->sp_id);
            $this->_bulid_result('404', 'bk inner error', null, $this->function);
            exit();
        }
        $clip_file_encode_enable_flag = true;
        $nns_date = str_replace('.', '', $_GET['nns_date']);
        $nns_date = str_replace('/', '', $nns_date);
        if ($state == TASK_C_STATE_OK)
        {
            \m_config::write_clip_receive_log('切片完成，生成注入xml文件，执行影片注入命令', $this->sp_id);
            $set_state['nns_date'] = $nns_date;
            $set_state['nns_end_time']=$dt;
            $set_state['nns_file_hit']=$nns_file_hit;
            $set_state['nns_priority']=0;
            //是否需要进行转码
            if(isset($this->sp_config['clip_file_encode_enable']) && $this->sp_config['clip_file_encode_enable'] == 1 && in_array($task_info['nns_video_type'], array('0','1')))
            {
                $video_info = clip_task_model::get_back_info_one(($task_info['nns_video_type'] == '0') ? 'media' : 'live_media',array('nns_id'=>$task_info['nns_video_media_id']));
                if (is_array($video_info) && !empty($video_info))
                {
                    if($this->_get_cp_config($video_info['nns_cp_id']) && isset($this->cp_config['cp_transcode_file_enabled']) && $this->cp_config['cp_transcode_file_enabled'] == '1')
                    {
                        $set_state['nns_state'] = TASK_C_STATE_CLIP_ENCODE_WAIT;
                        $clip_file_encode_enable_flag = false;
                    }
                }
            }
        }
        if($state == TASK_C_STATE_DOWNLOAD_FAIL || TASK_C_STATE_DOWNLOAD_SUCC)
        {
            $nns_clip_state = ($state == TASK_C_STATE_DOWNLOAD_SUCC) ? 3 : 4;
            $result_edit_meida = \nl_vod_media_v2::edit($this->obj_dc,array('nns_clip_state'=>$nns_clip_state),$task_info['nns_video_media_id']);
            if($result_edit_meida['ret'] !=0)
            {
                \m_config::write_clip_receive_log('修改片源切片状态数据内部错误：' . var_export($result_edit_meida, true), $this->sp_id);
                $this->_bulid_result('404', 'bk inner error', null, $this->function);
                exit();
            }
        }
        $set_state['nns_tom3u8_id'] = $tom3u8_id;
        $set_state['nns_new_dir'] = $nns_new_dir;

        //处理失败反馈
        if($state == TASK_C_STATE_DOWNLOAD_FAIL || $state == TASK_C_STATE_GET_MEDIA_URL_FAIL || $state == TASK_C_STATE_CLIP_FAIL
            || $state == TASK_C_STATE_C2_FAIL || $state == TASK_C_STATE_C2_DELETE_FAIL || $state == TASK_C_STATE_GET_DRM_KEY_FAIL
            || $state == TASK_C_STATE_CLIP_DRM_FAIL || $state == TASK_C_STATE_CLIP_ENCODE_FAIL|| $state == TASK_C_STATE_CLIP_UPLOAD_FAIL )
        {
            $this->message_feedback($task_info['nns_op_id'],$import_info,1, $this->task_state_arr[$state]);
        }

        //直播转点播
        if(($state == TASK_C_STATE_DOWNLOAD_FAIL || $state == TASK_C_STATE_GET_MEDIA_URL_FAIL || $state == TASK_C_STATE_CLIP_FAIL
                || $state == TASK_C_STATE_C2_FAIL || $state == TASK_C_STATE_C2_DELETE_FAIL || $state == TASK_C_STATE_GET_DRM_KEY_FAIL
                || $state == TASK_C_STATE_CLIP_DRM_FAIL || $state == TASK_C_STATE_CLIP_ENCODE_FAIL || $state == TASK_C_STATE_OK ||$state == TASK_C_STATE_CLIP_UPLOAD_FAIL ) &&
            isset($this->cp_config['cp_playbill_to_media_enabled']) && $this->cp_config['cp_playbill_to_media_enabled'] == '1' && isset($this->cp_config['source_notify_url']) && strlen($this->cp_config['source_notify_url']) >0)
        {
            \m_config::write_clip_receive_log('直播转点播切片状态反馈给epg开始：状态为：' . $state . ',task数据为：' . var_export($task_info, true), $this->sp_id);
            $nns_mgtvbk_op_queue = nl_op_queue::query_by_id($this->obj_dc, $task_info['nns_op_id']);
            \m_config::write_clip_receive_log('直播转点播切片状态反馈给epg开始：获取对列数据为：' . var_export($nns_mgtvbk_op_queue, true), $this->sp_id);
            if($nns_mgtvbk_op_queue['ret'] == 0 && isset($nns_mgtvbk_op_queue['data_info'][0]['nns_message_id']) && strlen($nns_mgtvbk_op_queue['data_info'][0]['nns_message_id']) >0)
            {
                if($state == TASK_C_STATE_OK)
                {
                    $result_encode = array(
                        'data_info' => $nns_mgtvbk_op_queue[0]['nns_message_id'],
                        'ret' => 0,
                        'reason' => TASK_C_STATE_OK,
                    );
                }
                else
                {
                    $result_encode = array(
                        'data_info' => $nns_mgtvbk_op_queue[0]['nns_message_id'],
                        'ret' => 1,
                        'reason' => $state,
                    );
                }
                \m_config::write_clip_receive_log('直播转点播切片失败状态直接反馈给epg开始：参数为：' . var_export($result_encode, true), $this->sp_id);
                $re_feedback = $this->notify_cp_sp_playbill_to_video($result_encode, $this->cp_config['source_notify_url']);
                \m_config::write_clip_receive_log('直播转点播切片失败状态直接反馈给epg完成：状态' . var_export($re_feedback, true), $this->sp_id);
            }
        }


        /*****先处理失败反馈*****/
        clip_task_model::update_task($task_id, $set_state);
        //查询此服务器id是否存在 不存在自动添加
        $result = \nl_clip_servicers::query_by_id($this->obj_dc, $tom3u8_id);
        if (!isset($result['data_info']) || empty($result['data_info']))
        {
            $params['nns_id']=np_guid_rand();
            $params['nns_tom3u8_id']=$tom3u8_id;
            \nl_clip_servicers::add($this->obj_dc, $params);
        }
        \m_config::write_clip_receive_log('更新内容：' . var_export($set_state, true), $this->sp_id);
        //在此进行上报
        if ($state == TASK_C_STATE_OK)
        {
            clip_task_model::q_clip_ok_push($task_id, $nns_date, $nns_new_dir, $nns_path, $nns_file_size, $nns_file_md5,$nns_cdn_policy,$nns_node_id,$nns_list_ids,$this->sp_config);

            if($clip_file_encode_enable_flag)
            {
                clip_task_model::task_progress($this->obj_dc, $task_id, array('nns_status' => NS_CDS_OP_WAIT));
            }
        }
        //任务日志
        $task_log = array (
            'nns_task_id' => $task_id,
            'nns_state' => $state,
            'nns_desc' => $desc,
            'nns_create_time' => $dt
        );
        clip_task_model::add_task_log($task_log);
        $data = '<result state="0" reason="OK" />';
        \m_config::write_clip_receive_log('任务日志：' . var_export($task_log, true), $this->sp_id);
        $this->_bulid_result('200', 'OK', $data, $this->function);
    }


    /**
     * 任务不存在或者任务已经注入成功，则可以删除
     * @authorliangpan
     * @date 2015-12-25
     */
    public function delete_clip_file()
    {
        \m_config::write_clip_receive_log('------' . $this->function . '------', $this->sp_id);
        $task_id = isset($_GET['nns_task_id']) ? $_GET['nns_task_id'] : null;
        $nns_new_dir = isset($_GET['nns_new_dir']) ? (empty($_GET['nns_new_dir']) ? false : true) : false;
        $result = clip_task_model::can_delete_clip_file_new($task_id); //判断分集ID所在的所有任务ID是否可以删除
        //}
        if ($result)
        {
            $data = '<result state="0" reason="allow delete" />';
            $this->_bulid_result('200', 'OK', $data, $this->function);
        }
        else
        {
            $data = '<result state="1" reason="not allowed delete" />';
            $this->_bulid_result('200', 'OK', $data, $this->function);
        }
    }

    /**
     * 获取DRM密钥
     * @return xml
     * @authorliangpan
     * @date 2015-12-25
     */
    public function get_drm_key()
    {
        \m_config::write_clip_receive_log('------' . $this->function . '------', $this->sp_id);
        $content_id = isset($_GET['content_id']) ? $_GET['content_id'] : null;
        $type = isset($_GET['nns_type']) ? $_GET['nns_type'] : null;
        $par = isset($_GET['nns_par']) ? $_GET['nns_par'] : null;
        $cp_id = isset($_GET['nns_cp_id']) ? trim($_GET['nns_cp_id']) : null;
        $this->cp_id = $cp_id = (strlen($cp_id) > 0) ? $cp_id : 0;
        $video_type= (isset($_GET['nns_video_type']) && strlen(trim($_GET['nns_video_type'])) >0) ? trim($_GET['nns_video_type']) : 0;
        $video_type = in_array($video_type, array(0,1)) ? $video_type : 0;
        $array_attr_result = array (
            'state' => 1,
            'drm_key' => '',
            'reason' => '',
            'type' => $type,
            'par' => $par
        );
        $this->obj_dom = new DOMDocument("1.0", 'utf-8');
        if (strlen($content_id) <1 || empty($type))
        {
            \m_config::write_clip_receive_log('取DRM密钥key失败:内容ID、类型不能为空', $this->sp_id);
            $array_attr_result['reason'] = 'params error';
            $this->make_xml('result', null, $array_attr_result);
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
        //查询drm配置
        $is_drm_config = $this->check_drm_action();
        //播控服务器内部失败
        if ($is_drm_config === false)
        {
            $array_attr_result['reason'] = 'bk inside fail';
            $this->make_xml('result', null, $array_attr_result);
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
        //播控DRM 开关关闭
        else if ($is_drm_config === true)
        {
            $array_attr_result['reason'] = 'drm config turn off';
            \m_config::write_clip_receive_log('获取DRM密钥：drm config turn off', $this->sp_id);
            $this->make_xml('result', null, $array_attr_result);
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
        //切片前开关打开  走以前drm老逻辑  （Verimatrix DRM加密）
        if ($is_drm_config === 0)
        {
            $array_attr_result['drm_type'] = 0;
            \ns_core\m_load::load_np('np_http_curl.class.php');
            $curl = new np_http_curl_class();

            $str_drm_key_url = defined('DRM_KEY_URL') ? DRM_KEY_URL : '';
            if(strlen($str_drm_key_url) < 1)
            {
                $str_drm_key_url = (isset($this->sp_config['q_drm_key_file_url']) && strlen($this->sp_config['q_drm_key_file_url']) > 0) ? : '';
            }
            if(strlen($str_drm_key_url) < 1)
            {
                $str_drm_key_url = (isset($this->cp_config['q_drm_key_file_url']) && strlen($this->cp_config['q_drm_key_file_url']) > 0) ? : '';
            }
            if(strlen($str_drm_key_url) < 1)
            {
                \m_config::write_clip_receive_log('取DRM密钥key失败:q_drm_key_file_url参数为空：' . var_export($str_drm_key_url, true), $this->sp_id);
                $array_attr_result['reason'] = 'get drm key url not set';
                $this->make_xml('result', null, $array_attr_result);
                $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
            }
            $url = $str_drm_key_url . 't=' . $type . '&p=' . $par . '&r=' . $content_id;
            $re = $curl->get($url);
            if (!$re)
            {
                \m_config::write_clip_receive_log('取DRM密钥key失败:CURL失败' . var_export($re, true), $this->sp_id);
                $array_attr_result['reason'] = 'get drm key fail';
                $this->make_xml('result', null, $array_attr_result);
                $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
            }
            //$re = pack("H16",strtolower($re));var_export($re);die;
            $re = bin2hex($re);
            $array_attr_result['state'] = 0;
            $array_attr_result['drm_key'] = $re;
            $array_attr_result['drm_type'] = 0;
            $array_attr_result['reason'] = 'OK';
            $result = $this->make_xml('result', null, $array_attr_result);
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
        //切片后开关打开   新逻辑 （ 数字太和 DRM 加密）
        else if($is_drm_config === 1)
        {
            $this->get_data_info($array_attr_result,$video_type,$content_id, $cp_id);
            $array_attr_result['drm_type'] = 1;
            $flag_sp_config = (!isset($this->sp_config['clip_drm_config_params']) || !is_array($this->sp_config['clip_drm_config_params'])) ? false : true;
            $flag_cp_config = (!isset($this->cp_config['clip_drm_config_params']) || !is_array($this->cp_config['clip_drm_config_params'])) ? false : true;
            if ($flag_sp_config === false && $flag_cp_config === false)
            {
                if($flag_sp_config === false)
                {
                    \m_config::write_clip_receive_log('获取SP数字太和配置文件配置失败' . var_export($this->sp_config['clip_drm_config_params'], true), $this->sp_id);
                }
                if($flag_cp_config === false)
                {
                    \m_config::write_clip_receive_log('获取CP数字太和配置文件配置失败' . var_export($this->cp_config['clip_drm_config_params'], true), $this->sp_id);
                }
                $array_attr_result['reason'] = 'clip drm config error';
                $array_attr_result['drm_key'] = '';
                $this->make_xml('result', null, $array_attr_result);
                $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
            }
            $array_attr_result['state'] = 0;
            $array_attr_result['reason'] = 'OK';
            $array_attr_result['drm_key'] = '';
            $result = $this->make_xml('result', null, $array_attr_result);
            $drm_param_list = $this->make_xml('drm_param_list',null,null,$result);
            $this->make_xml('program_name', $this->program_name,null,$drm_param_list);
            $this->make_xml('content_description', $this->content_description,null,$drm_param_list);
            if($flag_sp_config)
            {
                foreach ($this->sp_config['clip_drm_config_params'] as $key => $val)
                {
                    $this->make_xml($key, $val,null,$drm_param_list);
                }
            }
            else
            {
                foreach ($this->cp_config['clip_drm_config_params'] as $key => $val)
                {
                    $this->make_xml($key, $val,null,$drm_param_list);
                }
            }
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
        //Marlin DRM 加密
        else if($is_drm_config === 2)
        {
            #TODO
            $this->get_data_info($array_attr_result,$video_type,$content_id, $cp_id);
            $array_attr_result['drm_type'] = 2;
            if(strlen($this->drm_ext_info) <1)
            {
                $array_attr_result['reason'] = 'clip media make ext info error';
                $array_attr_result['drm_key'] = '';
                \m_config::write_clip_receive_log('获取片源扩展信息失败' . var_export($this->drm_ext_info, true), $this->sp_id);
                $this->make_xml('result', null, $array_attr_result);
                $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
            }
            $arr_drm_ext_data = json_decode($this->drm_ext_info,true);
            if(empty($arr_drm_ext_data) || !is_array($arr_drm_ext_data))
            {
                $array_attr_result['reason'] = 'clip media make ext info empty';
                $array_attr_result['drm_key'] = '';
                \m_config::write_clip_receive_log('获取片源扩展信息失败empty' . var_export($arr_drm_ext_data, true), $this->sp_id);
                $this->make_xml('result', null, $array_attr_result);
                $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
            }
            $array_attr_result['state'] = 0;
            $array_attr_result['reason'] = 'OK';
            $arr_drm_ext_data_keys = array_keys($arr_drm_ext_data);
            $str_key = $arr_drm_ext_data_keys[array_rand($arr_drm_ext_data_keys)];
            $str_val = $arr_drm_ext_data[$str_key];
            $array_attr_result['drm_key'] = $str_val;
            $array_attr_result['par'] = $str_key;
            $this->make_xml('result', null, $array_attr_result);
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
        else
        {
            \m_config::write_clip_receive_log('不存在此drm加密模式'.var_export($is_drm_config,true), $this->sp_id);
            $array_attr_result['reason'] = 'no such drm model';
            $this->make_xml('result', null, $array_attr_result);
            $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
        }
    }

    /**
     * 获取直播、点播名称/描述等信息
     * @param array $array_attr_result 组装xml的数据数组
     * @param int $video_type 影片类型  0 点播 | 1 直播
     * @param string $content_id 注入id
     * @param string $cp_id cp_id
     * @authorliangpan
     * @date 2015-12-25
     */
    private function get_data_info($array_attr_result,$video_type,$content_id, $cp_id)
    {
        switch ($video_type)
        {
            case 0:
                \ns_core\m_load::load_old('nn_logic/video/vod_index.class.php');
                \ns_core\m_load::load_old('nn_logic/video/vod_media.class.php');
                \ns_core\m_load::load_old('nn_logic/video/vod.class.php');
                $result_media = nl_vod_media_v2::get_video_index_info_by_import_id($this->obj_dc, $content_id, $cp_id);
                if ($result_media['ret'] != 0)
                {
                    \m_config::write_clip_receive_log($result_media['reason'], $this->sp_id);
                    $array_attr_result['reason'] = 'bk inside fail';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                if (!isset($result_media['data_info'][0]) || !is_array($result_media['data_info'][0]))
                {
                    \m_config::write_clip_receive_log('未找到该片源信息,上传参数为：' . var_export($_GET, true), $this->sp_id);
                    $array_attr_result['reason'] = 'no media find';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                $result_index = nl_vod_index::get_video_index_info_by_id($this->obj_dc, $result_media['data_info'][0]['nns_vod_index_id']);
                $result_video = nl_vod::get_video_info_by_id($this->obj_dc, $result_media['data_info'][0]['nns_vod_id']);
                if ($result_index['ret'] != 0)
                {
                    \m_config::write_clip_receive_log($result_index['reason'], $this->sp_id);
                    $array_attr_result['reason'] = 'bk inside fail';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                if (!isset($result_index['data_info'][0]) || !is_array($result_index['data_info'][0]))
                {
                    \m_config::write_clip_receive_log('未找到该分集信息,分集id为：' . $result_media['data_info'][0]['nns_vod_index_id'], $this->sp_id);
                    $array_attr_result['reason'] = 'no index find';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                if ($result_video['ret'] != 0)
                {
                    \m_config::write_clip_receive_log($result_video['reason'], $this->sp_id);
                    $array_attr_result['reason'] = 'bk inside fail';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                if (!isset($result_video['data_info'][0]) || !is_array($result_video['data_info'][0]))
                {
                    \m_config::write_clip_receive_log('未找到该主媒资信息,主媒资id为：' . $result_media['data_info'][0]['nns_vod_id'], $this->sp_id);
                    $array_attr_result['reason'] = 'no vod find';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                $result_index['data_info'][0]['nns_index']++;
                $this->program_name = "[点播] [{$result_video['data_info'][0]['nns_name']}] [第{$result_index['data_info'][0]['nns_index']}集] {$result_media['data_info'][0]['nns_mode']}";
                $this->content_description =  $result_index['data_info'][0]['nns_summary'];
                $this->drm_ext_info = $result_media['data_info'][0]['nns_drm_ext_info'];
                break;
            case 1:
                \ns_core\m_load::load_old('nn_logic/video/live_media.class.php');
                \ns_core\m_load::load_old('nn_logic/video/live.class.php');
                $result_media=nl_live_media::get_live_media_info_by_import_id($this->obj_dc, $content_id, $cp_id);
                if ($result_media['ret'] != 0)
                {
                    \m_config::write_clip_receive_log($result_media['reason'], $this->sp_id);
                    $array_attr_result['reason'] = 'bk inside fail';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                if (!isset($result_media['data_info'][0]) || !is_array($result_media['data_info'][0]))
                {
                    \m_config::write_clip_receive_log('未找到该片源信息,上传参数为：' . var_export($_GET, true), $this->sp_id);
                    $array_attr_result['reason'] = 'no live media find';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                $result_live = nl_live::get_live_info_by_id($this->obj_dc, $result_media['data_info'][0]['nns_live_id'],$cp_id);
                if ($result_live['ret'] != 0)
                {
                    \m_config::write_clip_receive_log($result_live['reason'], $this->sp_id);
                    $array_attr_result['reason'] = 'bk inside fail';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                if (!isset($result_live['data_info'][0]) || !is_array($result_live['data_info'][0]))
                {
                    \m_config::write_clip_receive_log('未找到该主媒资信息,主媒资id为：' . $result_live['data_info'][0]['nns_live_id'], $this->sp_id);
                    $array_attr_result['reason'] = 'no live find';
                    $this->make_xml('result', null, $array_attr_result);
                    $this->_bulid_result('200', 'OK', $this->obj_dom->saveXML(), $this->function, false);
                }
                $this->program_name = "[直播] [{$result_live['data_info'][0]['nns_name']}] {$result_media['data_info'][0]['nns_mode']}";
                $this->content_description =  $result_live['data_info'][0]['nns_summary'];
                $this->drm_ext_info = $result_media['data_info'][0]['nns_drm_ext_info'];
                break;
            default:
                break;
        }
        return ;
    }


    /**
     * 组装基础dom对象类
     * @param string $key 键
     * @param string $val 值
     * @param array $arr_attr attr值
     * @param object $parent 父级对象
     * @return object
     * @date 2015-05-04
     */
    private function make_xml($key, $val = null, $arr_attr = null,$parent=null)
    {
        if(is_null($parent))
        {
            $parent=$this->obj_dom;
        }
        $$key = isset($val) ? $this->obj_dom->createElement($key, $val) : $this->obj_dom->createElement($key);
        if (!empty($arr_attr) && is_array($arr_attr))
        {
            foreach ($arr_attr as $attr_key => $attr_val)
            {
                $domAttribute = $this->obj_dom->createAttribute($attr_key);
                $domAttribute->value = $attr_val;
                $$key->appendChild($domAttribute);
                $this->obj_dom->appendChild($$key);
            }
        }
        $parent->appendChild($$key);
        //unset($dom);
        unset($parent);
        return $$key;
    }

    /**
     * 检查切片中是否需要drm验证
     * @return bool|int
     */
    private function check_drm_action()
    {
        if (empty($this->sp_id))
        {
            \m_config::write_clip_receive_log('检查运营商id为空：' . var_export($this->sp_id, true), $this->sp_id);
            if(strlen($this->cp_id) <1)
            {
                \m_config::write_clip_receive_log('检查CP_id为空：' . var_export($this->cp_id, true), $this->sp_id);
                return false;
            }
        }
        \ns_core\m_load::load_old('nn_logic/sp/sp.class.php');
        $result_sp = nl_sp::query_by_id($this->obj_dc, $this->sp_id);
        if ($result_sp['ret'] != 0)
        {
            \m_config::write_clip_receive_log('查询sp配置信息数据库错误：'.var_export($result_sp, true), $this->sp_id);
            return false;
        }
        if (!isset($result_sp['data_info'][0]))
        {
            \m_config::write_clip_receive_log('SP查询没有运营商信息：' . var_export($result_sp, true), $this->sp_id);
            return false;
        }
        $this->sp_config = (isset($result_sp['data_info'][0]['nns_config']) && !empty($result_sp['data_info'][0]['nns_config'])) ? json_decode($result_sp['data_info'][0]['nns_config'], true) : array ();
        if (!isset($this->sp_config['main_drm_enabled']) || $this->sp_config['main_drm_enabled'] != 1)
        {
            \m_config::write_clip_receive_log('SP配置drm主开关关闭', $this->sp_id);
        }
        if (isset($this->sp_config['q_disabled_drm']) && $this->sp_config['q_disabled_drm'] == 1)
        {
            return 0;
        }
        if (isset($this->sp_config['clip_drm_enabled']) && $this->sp_config['clip_drm_enabled'] == 1)
        {
            return 1;
        }
        \ns_core\m_load::load_old('nn_logic/cp/cp.class.php');
        $result_cp= nl_cp::query_by_id($this->obj_dc, $this->cp_id);
        if ($result_cp['ret'] != 0)
        {
            \m_config::write_clip_receive_log('查询CP配置信息数据库错误，可能是此播控版本cp表不存在：cp为'.$this->cp_id . var_export($result_cp, true), $this->sp_id);
            return true;
        }
        if (!isset($result_cp['data_info']))
        {
            \m_config::write_clip_receive_log('查询没有CP信息：cp为'.$this->cp_id . var_export($result_cp, true), $this->sp_id);
            return true;
        }
        $this->cp_config = (isset($result_cp['data_info']['nns_config']) && !empty($result_cp['data_info']['nns_config'])) ? json_decode($result_cp['data_info']['nns_config'], true) : array ();
        if (!isset($this->cp_config['main_drm_enabled']) || $this->cp_config['main_drm_enabled'] != 1)
        {
            \m_config::write_clip_receive_log('CP配置drm主开关关闭', $this->sp_id);
            return true;
        }
        if (isset($this->cp_config['q_disabled_drm']) && $this->cp_config['q_disabled_drm'] == 1)
        {
            return 0;
        }
        if (isset($this->cp_config['clip_drm_enabled']) && $this->cp_config['clip_drm_enabled'] == 1)
        {
            return 1;
        }
        if (isset($this->cp_config['q_marlin_drm_enable']) && $this->cp_config['q_marlin_drm_enable'] == 1)
        {
            return 2;
        }
        \m_config::write_clip_receive_log('drm开关关闭', $this->sp_id);
        return true;
    }

    /**
     * 组装返回的xml文件
     * @param int $http_code http状态码
     * @param string $resson 原因描述
     * @param string $data xml格式的字符串
     * @authorliangpan
     * @date 2015-12-25
     */
    public function _bulid_result($http_code, $resson, $data = null, $function = 'public', $is_need_header = true)
    {
        header('HTTP/1.1 ' . $http_code . ' ' . $resson);
        header('Status: ' . $http_code . ' ' . $resson);
        header("Content-Type:text/xml;charset=utf-8");
        $str_header = $is_need_header ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
        $str_header = strpos($data,'<?xml') === false ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
        $data = ($data != null) ? $str_header . $data : '';
        \m_config::write_clip_receive_log('原因描述：' . var_export($resson, true), $this->sp_id);
        \m_config::write_clip_receive_log('返回结果：' . $data, $this->sp_id);
        echo $data;
        die();
    }

    /**
     * 切片信息消息反馈
     * @param $op_queue_id
     * @param $import_info
     * @param int $state 0 成功 1 失败 [注入平台统一0成功 1失败]
     * @param string $str_message
     * @authorliangpan
     * @date 2017-02-20
     */
    public function message_feedback($op_queue_id, $import_info, $state=1, $str_message='download fail')
    {
        \m_config::write_clip_receive_log("---切片消息反馈开始---参数：".var_export(func_get_args(),true), $this->sp_id);
        \ns_core\m_load::load_old('nn_logic/project_group/project_group.class.php');
        \ns_core\m_load::load_old('nn_logic/op_queue/op_queue.class.php');
        if(strlen($this->cp_id) < 1)
        {
            \m_config::write_clip_receive_log("CP id 错误，传入参数为：".var_export($this->cp_id,true), $this->sp_id);
            nn_log::write_log_message('clip_log', "CP id 错误，传入参数为：".var_export($this->cp_id,true), $this->sp_id, $this->function);
            return ;
        }
        $result_op_queue = nl_op_queue::query_op_queue_info_by_id($this->obj_dc,$op_queue_id);
        if($result_op_queue['ret'] !=0)
        {
            \m_config::write_clip_receive_log("查询OP_QUEUE队列信息:".$result_op_queue['reason'], $this->sp_id);
            return ;
        }
        if(!is_array($result_op_queue['data_info'][0]) || empty($result_op_queue['data_info'][0]))
        {
            \m_config::write_clip_receive_log("查询OP_QUEUE队列信息为空，错误", $this->sp_id);
            return ;
        }
        $item = array(
            'nns_message_id' => $result_op_queue['data_info'][0]['nns_message_id'],
            'nns_action' => $result_op_queue['data_info'][0]['nns_action'],
            'nns_org_id' => $result_op_queue['data_info'][0]['nns_org_id'],
        );

        /********反馈走新版 xinxin.deng 2018/7/9 15:45   start********/
        $project = evn::get("project");
        $classname = \ns_core\m_load::load("ns_api.{$project}.message.{$this->cp_id}.message");
        $obj_feedback_v2 = new message();
        if ($classname)
        {
            $arr_info = array(
                'cdn_id' => '',
                'site_id' => $this->sp_config['site_id'],
                'mg_asset_type' => 3,
                'mg_asset_id' => $import_info[0]['video_import_id'],
                'mg_part_id' => $import_info[0]['index_import_id'],
                'mg_file_id' => $import_info[0]['media_import_id'],
            );
            //兼容湖南电信二级消息反馈，1表示成功，0表示失败。
            //$code = $state === 1 ? 0 : 1;
            $obj_feedback_v2->is_ok($item['nns_message_id'], $state, $str_message, $arr_info, $this->sp_id);
            unset($obj_feedback_v2);
        }
        /********新版未迁移切片，但反馈走新版 xinxin.deng 2018/7/9 15:45   end********/
        return ;
    }

    /**
     * 消息反馈
     * @param $result_encode
     * @param $url
     * @return multitype
     */
    public function notify_cp_sp_playbill_to_video($result_encode,$url)
    {

        $playbill_info = array(
            'id'=>$result_encode['data_info'],
            'state'=>$result_encode['ret'] == 0 ? 2 : 3,
            'summary'=>$result_encode['reason'],
        );
        return $this->_execute_curl($url,'post',array('a'=>'update_vod_playbill_transcode_state','playbill_info'=>json_encode(array($playbill_info))));
    }

    /**
     * 执行curl
     * @param $send_url
     * @param string $func
     * @param null $content
     * @param null $arr_header
     * @param int $time
     * @return array
     */
    public function _execute_curl($send_url,$func='get',$content=null,$arr_header=null,$time=60)
    {
        $obj_curl = new np_http_curl_class();
        $curl_data = $obj_curl->do_request($func,$send_url,$content,$arr_header,60);
        $curl_info = $obj_curl->curl_getinfo();
        $http_code = $curl_info['http_code'];
        if($curl_info['http_code'] != '200')
        {
            return $this->_return_data(1,'[访问第三方接口,CURL接口地址]：'.$send_url.'[HTTP状态码]：'.$curl_info['http_code'].'[HTTP错误]：'.$obj_curl->curl_error(),$curl_data);
        }
        else
        {
            return $this->_return_data(0,'[访问第三方接口,CURL接口地址]：'.$send_url,$curl_data);
        }
    }
}